package cn.jbt.api.admin.service;

import cn.hutool.core.util.IdUtil;
import cn.jbt.config.AliyunOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
public class AliyunOssService {

    private final ISysConfigService iSysConfigService;

    public Map<String, Object> upload(MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        // 最大 100M
        long limitMax = 100 * 1024 * 1024;
        if (file.getSize() >= limitMax) {
            throw new RuntimeException("文件大小限制");
        }

        AliyunOssConfig aliyunOss = (AliyunOssConfig) iSysConfigService.getConfig("AliyunOss");
        OSS ossClient = new OSSClientBuilder().build(aliyunOss.getEndpoint(),
                aliyunOss.getAccessKeyID(), aliyunOss.getAccessKeySecret());

        // 源文件名
        String originalName = file.getOriginalFilename();

        assert originalName != null;
        // 文件拓展名
        String ext = originalName.substring(originalName.lastIndexOf("."));
        // 文件存储名
        String storeName = IdUtil.randomUUID() + ext;

        // 限制上传的文件前缀。
        String dir = String.format("%s", new SimpleDateFormat("yyyyMMdd").format(new Date()));

        String objectName = dir + "/" + storeName;
        PutObjectResult putObjectResult = ossClient.putObject(
                aliyunOss.getBucket(), objectName, file.getInputStream()
        );
        log.info("PutObjectResult: [{}]", putObjectResult);

        Map<String, Object> result = new HashMap<>();
        result.put("url", String.format("https://%s.%s/%s", aliyunOss.getBucket(), aliyunOss.getEndpoint(), objectName));
        result.put("name", storeName);
        return result;
    }

}
